<template>
  <el-dialog
    :title="`${drawerProps.title}项目`"
    v-model="drawerVisible"
    :draggable="true"
    :overflow="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="30px"
    width="1400px"
    :destroy-on-close="true"
  >
    <el-form
      ref="ruleFormRef"
      style="height: 70vh; overflow: hidden auto"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-row>
        <el-col :span="16">
          <group-title title="基本信息"></group-title>
          <el-row>
            <form-item title="项目编号" prop="item_no" :title-span="3" :item-span="5">
              <el-input v-model="drawerProps.row!.item_no" clearable></el-input>
            </form-item>
            <form-item title="年度" prop="year" :title-span="3" :item-span="5">
              <el-date-picker type="year" v-model="drawerProps.row!.year" placeholder="请选择年度"></el-date-picker>
            </form-item>
            <form-item title="项目名称" prop="name" :title-span="3" :item-span="5">
              <el-input v-model="drawerProps.row!.name" clearable></el-input>
            </form-item>
          </el-row>
          <el-row>
            <form-item title="立项时间" prop="start_date" :title-span="3" :item-span="5">
              <el-date-picker type="date" v-model="drawerProps.row!.start_date" placeholder="请选择"></el-date-picker>
            </form-item>
            <form-item title="项目级别" prop="level" :title-span="3" :item-span="5">
              <common-select
                placeholder="请选择项目等级"
                data-key="ITEM_LEVEL"
                :request-api="() => apiService.findClassify('ITEM_LEVEL')"
                v-model="drawerProps.row!.level"
              ></common-select>
            </form-item>
            <form-item title="项目类别" prop="classify" :title-span="3" :item-span="5">
              <cascader-select
                data-key="ITEM_CLASSIFY"
                :request-api="() => apiService.findTree('param_exts', { csName: 'ITEM_CLASSIFY' })"
                :config="{ label: 'name', value: '_id' }"
                v-model:item-value="drawerProps.row!.classify"
              ></cascader-select>
            </form-item>
          </el-row>
          <el-row>
            <form-item title="客户" prop="customer" :title-span="3" :item-span="5">
              <cascader-select
                data-key="customer_classify"
                :request-api="() => apiService.findTree('param_exts', { csName: 'customer_classify' })"
                :config="{ label: 'name', value: '_id' }"
                v-model:item-value="drawerProps.row!.customer"
              ></cascader-select>
            </form-item>
            <form-item title="主产品" prop="main_product" :title-span="3" :item-span="5">
              <product-select placeholder="请选择产品" v-model="drawerProps.row!.main_product"></product-select>
            </form-item>
            <form-item title="辅产品" prop="support_product" :title-span="3" :item-span="5">
              <product-select
                placeholder="请选择产品"
                :multiple="true"
                v-model="drawerProps.row!.support_product"
              ></product-select>
            </form-item>
          </el-row>
          <el-row>
            <form-item title="项目简介" prop="summary" :title-span="3" :item-span="21">
              <WangEditor height="200px" v-model:value="drawerProps.row.summary" :editor-config="editConfig" />
            </form-item>
          </el-row>

          <group-title title="交付情况"></group-title>
          <el-row>
            <form-item title="预计交付时间" prop="plan_completion_date" :title-span="3" :item-span="5">
              <el-date-picker type="date" v-model="drawerProps.row!.plan_completion_date" placeholder="请选择"></el-date-picker>
            </form-item>
            <form-item title="实际交付时间" :title-span="3" :item-span="5">
              <el-date-picker type="date" v-model="drawerProps.row!.completion_date" placeholder="请选择"></el-date-picker>
            </form-item>
            <form-item title="项目状态" prop="state" :title-span="3" :item-span="5">
              <common-select
                placeholder="请选择项目状态"
                data-key="ITEM_STATE"
                :request-api="() => apiService.findClassify('ITEM_STATE')"
                v-model="drawerProps.row!.state"
              ></common-select>
            </form-item>
          </el-row>
          <group-title title="评论" v-if="drawerProps.row!._id"></group-title>
          <business-comment
            v-if="drawerProps.row!._id"
            :business-id="drawerProps.row!._id"
            :business-type="BusinessType.TASK"
          ></business-comment>
        </el-col>

        <el-col :offset="1" :span="7">
          <group-title title="干系人"></group-title>
          <el-row>
            <form-item title="研发产品组" prop="dev_org_id" :title-span="8" :item-span="14">
              <cascader-select
                data-key="orgs"
                :request-api="() => apiService.findTree('orgs', {}, { sort: { sort: 1 }, fields: ['_id', 'name', 'pid'] })"
                :config="{ label: 'name', value: '_id', checkStrictly: true }"
                v-model:item-value="drawerProps.row!.dev_org_id"
              ></cascader-select>
            </form-item>
            <form-item title="交付负责组" prop="release_org_id" :title-span="8" :item-span="14">
              <cascader-select
                data-key="orgs"
                :request-api="() => apiService.findTree('orgs', {}, { sort: { sort: 1 }, fields: ['_id', 'name', 'pid'] })"
                :config="{ label: 'name', value: '_id', checkStrictly: true }"
                v-model:item-value="drawerProps.row!.release_org_id"
              ></cascader-select>
            </form-item>
            <form-item title="交付负责人" prop="relase_charge_user" :title-span="8" :item-span="14">
              <user-select placeholder="请选择用户" v-model="drawerProps.row!.relase_charge_user"></user-select>
            </form-item>
            <form-item title="售前负责人" prop="pre_sale_user" :title-span="8" :item-span="14">
              <user-select placeholder="请选择用户" v-model="drawerProps.row!.pre_sale_user"></user-select>
            </form-item>
          </el-row>
          <group-title title="附件"></group-title>
          <el-row>
            <el-col :span="22">
              <UploadFiles v-model:file-list="drawerProps.row.files" :drag="false" border-radius="50%"></UploadFiles>
            </el-col>
          </el-row>
          <!-- <group-title v-if="drawerProps.row!._id" title="操作记录"></group-title>
          <el-row>
            <el-col :span="22">
              <business-action v-if="drawerProps.row!._id" :business-id="drawerProps.row!._id"></business-action>
            </el-col>
          </el-row> -->
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { ElMessage, ElNotification, FormInstance } from "element-plus";
import { Item } from "@/api/types/base";
import commonSelect from "@/components/SelectFilter/common-select.vue";
import apiService from "@/api/services/apiService";
import groupTitle from "@/components/application/form/group-title.vue";
import formItem from "@/components/application/form/form-item.vue";
import UploadFiles from "@/components/Upload/Files.vue";
import { BusinessOptType, BusinessType, MessageType } from "@/enums/sysEnum";
// import businessAction from "@/components/application/action/business-action.vue";
import businessComment from "@/components/application/comment/business-comment.vue";
import { useUserAction } from "@/hooks/useUserAction";
import { useMessage } from "@/hooks/useMessage";
import CascaderSelect from "@/components/SelectFilter/cascader-select.vue";
import productSelect from "@/components/SelectFilter/product-select.vue";
import userSelect from "@/components/SelectFilter/user-select.vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { IEditorConfig } from "@wangeditor/editor";

const { addUserAction } = useUserAction(BusinessType.TASK);
const { sendSysMessage } = useMessage(BusinessType.TASK);

const rules = reactive({
  item_no: [{ required: true, message: "请输入项目编号" }],
  name: [{ required: true, message: "请输入项目名称" }]
});

const editConfig: Partial<IEditorConfig> = {
  placeholder: "请输入项目详情……",
  MENU_CONF: {}
};

interface DrawerProps {
  title: string;
  tbName: string;
  isView: boolean;
  row: Partial<Item>;
  api?: (tabName: string, params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  tbName: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 查重
const checkRepeat = async (): Promise<boolean> => {
  let { data } = await apiService.findCount<number>(drawerProps.value.tbName, { item_no: drawerProps.value.row.item_no });
  return data > 0;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (drawerProps.value.title.indexOf("新增") != -1) {
        drawerProps.value.row!.create_at = new Date();
        if (await checkRepeat()) {
          ElNotification({
            title: "温馨提示",
            message: `项目编号重复请重新输入！`,
            type: "warning"
          });
          return;
        }
      }
      const data = await drawerProps.value.api!(drawerProps.value.tbName, drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}项目成功！` });

      if (drawerProps.value.title.indexOf("新增") != -1) {
        addUserAction(data._id, BusinessOptType.ADD, data.name);
        sendSysMessage(data._id, data.name, data.summary, MessageType.TODO, [data.user_id]);
      } else {
        addUserAction(drawerProps.value.row._id, BusinessOptType.UPDATE, drawerProps.value.row.name);
      }

      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
